<template>
  <div>
    <!-- 面包屑 区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 警告框 -->
      <el-alert class="alert" title="添加商品信息" type="info" show-icon center>
      </el-alert>
      <!-- 步揍区域 -->
      <el-steps
        :space="200"
        :active="Number(indexActive)"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 提交数据的表单 -->
      <el-form
        :model="addGood"
        :rules="addGoodRules"
        ref="addGoodRef"
        label-width="100px"
        class="demo-ruleForm"
        label-position="top"
        style="margin-top: 15px"
      >
        <!-- 侧边栏 -->
        <el-tabs
          v-model="indexActive"
          tab-position="left"
          :before-leave="beforeTabLeave"
          @tab-click="activeTag"
        >
          <!-- 表单的基本信息 -->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGood.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addGood.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addGood.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addGood.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="selectGood">
              <el-cascader
                v-model="addGood.goods_cat"
                :options="goodsList"
                :props="editProp"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyData"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  :label="item"
                  v-for="(item, index) in item.attr_vals"
                  :key="index"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyData"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :headers="iconToken"
              :action="iconURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :on-success="addIconForm"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 添加文本编辑器组件 -->
            <quill-editor
              ref="myQuillEditor"
              v-model="addGood.goods_introduce"
            />
            <!-- 添加按钮 -->
            <el-button type="primary" class="button" @click="add"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <el-dialog title="图片预览" :visible.sync="dialogVisible" width="50%">
      <img :src="iconAbsolutePath" alt="" width="100%" />
    </el-dialog>
  </div>
</template>
<script>
import _ from 'lodash'
export default {
  data () {
    return {
      indexActive: '0',
      // 提交的数据
      addGood: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 商品选中的id 是个数组
        goods_cat: [],
        pics: [],
        // 商品介绍
        goods_introduce: '',
        // 商品参数
        attrs: []
      },
      // 提交的规则
      addGoodRules: {
        goods_name: [
          {
            required: true,
            trigger: 'blur',
            message: '请输入商品名称'
          }
        ],
        goods_price: [
          {
            required: true,
            trigger: 'blur',
            message: '请输入商品价格'
          },
          {
            min: 1,
            trigger: 'blur',
            message: '最少为1'
          }
        ],
        goods_weight: [
          {
            required: true,
            trigger: 'blur',
            message: '请输入商品重量'
          },
          {
            min: 1,
            trigger: 'blur',
            message: '最少为1'
          }
        ],
        goods_number: [
          {
            required: true,
            trigger: 'blur',
            message: '请输入商品数量'
          },
          {
            min: 1,
            trigger: 'blur',
            message: '最少为1'
          }
        ],
        goods_cat: [
          {
            required: true,
            trigger: 'blur',
            message: '请输入商品数量'
          },
          {
            min: 1,
            trigger: 'blur',
            message: '最少为1'
          }
        ]
      },
      // 商品列表数据
      goodsList: [],
      //   级联选择器配置项
      editProp: {
        // 级联选择器标签名
        label: 'cat_name',
        // 商品分类的id 提交的真正数据
        value: 'cat_id',
        // 嵌套父子数据
        children: 'children',
        expandTrigger: 'hover'
      },
      // 获取的动态参数
      manyData: [],
      // 获取静态数据
      onlyData: [],
      // 上传的图片路径
      iconURL: 'http://www.ysqorz.top:8888/api/private/v1/upload',
      // 设置请求头
      iconToken: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 图片的显示
      dialogVisible: false,
      // 图片的路径
      iconAbsolutePath: ''
    }
  },
  created () {
    this.getGoodsList()
  },
  methods: {
    // 获取商品列表
    async getGoodsList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.message.error('获取商品列表失败')
      }
      this.goodsList = res.data
    },
    // 级联选择器选中项目
    handleChange () {
      if (this.addGood.goods_cat.length !== 3) {
        this.addGood.goods_cat = []
        return this.$message.error('应选三级分类')
      }
    },
    // 标签页离开时的方法
    beforeTabLeave (activeName, oldActiveName) {
      if (this.addGood.goods_cat.length !== 3) {
        this.$message.error('请选择商品列表')
        return false
      }
    },
    // 触发切换标签页的事件
    async activeTag () {
      // 判断是不是在动态标签面板
      if (this.indexActive === '1') {
        const { data: res } = await this.$http.get(
          `categories/${this.goodId}/attributes`,
          {
            params: {
              sel: 'many'
            }
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('获取动态失败')
        }
        // 获取每项的参数项
        res.data.forEach((element) => {
          // 对字符串分隔
          element.attr_vals = element.attr_vals.split(',')
        })
        this.manyData = res.data
        console.log(this.manyData)
        // 获取静态数据
      } else if (this.indexActive === '2') {
        const { data: res } = await this.$http.get(
          `categories/${this.goodId}/attributes`,
          {
            params: {
              sel: 'only'
            }
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('获取动态失败')
        }
        this.onlyData = res.data
        console.log(this.onlyData)
      }
    },
    // 图片预显示
    handlePreview (file) {
      console.log(file)
      console.log(file.response.data.tmp_path)
      // 获取绝对路径
      this.iconAbsolutePath =
        'http://www.ysqorz.top:8888/' + file.response.data.tmp_path

      console.log(this.iconAbsolutePath)
      this.dialogVisible = true
    },
    // 图片移除 参数是移除的信息对象
    handleRemove (file) {
      console.log(file)
      // 1 获取将要删除的图片路径
      const iconUrl = file.response.data.tmp_path
      // 2 从pices数组中找到图片路径 找到对应的索引
      const i = this.addGood.pics.findIndex((item) => {
        return item === iconUrl
      })
      // 3 调用数组的splice 方法把图片的信息对象从pics数组中移除
      this.addGood.pics.splice(i, 1)
    },
    // 将上传成功的图片放入到表单
    addIconForm (response) {
      console.log(response)
      // 拼接一个图片信息对象
      const iconUrl = {
        pic: response.data.tmp_path
      }
      // 添加到表单
      this.addGood.pics.push(iconUrl)
    },
    // 商品提交
    add () {
      this.$refs.addGoodRef.validate().then(async () => {
        // 对提交表单的分类数组进行拷贝
        const form = _.cloneDeep(this.addGood)
        form.goods_cat = form.goods_cat.join(',')
        console.log(form.goods_cat)
        // 对参数和属性做处理
        this.manyData.forEach(item => {
          // 对参数做处理
          const newMany = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          form.attrs.push(newMany)
        })
        // 对属性做处理
        this.onlyData.forEach(item => {
          const newOnly = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          form.attrs.push(newOnly)
        })
        const { data: res } = await this.$http.post('goods', form)
        console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error('添加失败')
        }
        this.$router.push('/goods')
        console.log(res.data)
      }).catch(() => {
        return this.$message.error('请填写基本信息')
      })
    }
  },
  computed: {
    // 获取商品分类的id
    goodId () {
      if (this.addGood.goods_cat.length !== 3) {
        return this.$message.error('请选择三级分类')
      }
      return this.addGood.goods_cat[this.addGood.goods_cat.length - 1]
    }
  }
}
</script>
<style   scoped>
.alert {
  margin-top: 15px;
}
.el-checkbox {
  margin: 0 15px 5px 0 !important;
}
.button {
  margin-top: 20px;
}
</style>
